﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;

/// <summary>
/// Summary description for Dzinejs
/// </summary>
public class Dzinejs
{
    public Dzinejs()
    {
        // TODO: Add constructor logic here
        //
    }
    private int Size1;
    private string istaisbildesPath;
    private string BildePath = "";
    private string Rtext = "";
    private string Vidaks = "";
    private int[] tag_start_Nr = new int[1];
    private string[] tag_text = new string[1];

    public string Bildes_Show_Mape
    {
        get { return BildePath; }
        set { BildePath = value; }
    }
    public int thumbSize
    {
        get { return Size1; }
        set { Size1 = value; }
    }

    public string IstaisBildesString
    {
        get { return istaisbildesPath; }
        set { istaisbildesPath = value; }
    }

    public string MakeMeAGoodThumbnail(string pathUplode, System.IO.Stream Object, string FileName, int SizeH, int SizeW)
    { // koments:  string pathUplode formāts = "C:\\UploadedUserFiles\\" .
        bool Horizontal = false;
        bool XYmode = false;
        float Procents = 0;
        // bool Vertical = false;
        System.Drawing.Bitmap bmp2 = new System.Drawing.Bitmap(Object);
        float bmpH = Convert.ToSingle(bmp2.Height);
        float bmpW = Convert.ToSingle(bmp2.Width);
        if (SizeH != 0)
        {
            Horizontal = true; //Size = SizeH;
            Size1 = SizeH;
            if (SizeW != 0)
            { // Salīdzina Proporcijas Bildei Vs PARAMETRiem
                XYmode = true;
                float S = Convert.ToSingle(SizeW);
                float T = Convert.ToSingle(SizeH);
                //float A = (S / T)*1000; // Convert.ToSingle(SizeW / SizeH);
                //float B =  (bmpW /bmpH)*1000;
                //int A = bmp2.Height;
                //int B = bmp2.Width;
                int A = Convert.ToInt32((SizeW * 1000) / SizeH);
                int B = ((bmp2.Width*1000)/bmp2.Height);

                if ( A < B)
                {
                    Horizontal = false;
                    Size1 = SizeW;
                }
                else
                {
                    Horizontal = true;
                    Size1 = SizeH;
                }
            }
        }
        else
        {
            if (SizeW != 0) { Size1 = SizeW; Horizontal = false; }
        }

        //if (SizeH != 0)
        //{ Horizontal = true; Size1 = SizeH; }
        //if (SizeW != 0) { Size1 = SizeW; }
        // Size = SizeW;
        string NewBildesString = "";
        // System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(FileField.FileContent);

        Int32 width, height;

            try
            {
                bmp2.Save(pathUplode + FileName); // save Image Orģināju
            }
            catch (Exception exp)
            {
                throw new Exception("Failu Nevar Saglabāt");
            }

            IstaisBildesString = BildePath + FileName;

            //these are just arbitary numbers -- if the image is larger than this, create a 100px max by 100px max thumbnail defined by the constant at the start
            if (bmp2.Height > SizeH && bmp2.Width > SizeW) 
            { // 2010.29 janvaris ieliku ||(OR) vietā &&(AND)...
                float percent = 0;
                if (Horizontal == true)
                {
                    percent = DeterminePercentageForResize(bmp2.Height);
                }
                else { percent = DeterminePercentageForResize(bmp2.Width); }

                float floatWidth = (float)bmp2.Width * percent;
                float floatHeight = (float)bmp2.Height * percent;
                width = Convert.ToInt32(floatWidth);
                height = Convert.ToInt32(floatHeight);
            }
            else
            {
                width = Convert.ToInt32(bmpW);
                height = Convert.ToInt32(bmpH);
            }
            string NewbildeName = "Small" + FileName;
            //Size newSize = new Size(width, height);
            string thumbnailFilePath = string.Empty;
                thumbnailFilePath = pathUplode + NewbildeName; //Change the thumbnail path if you want
                bmp2.Dispose();        
        System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(Object); 
        System.Drawing.Bitmap thumb2 = new System.Drawing.Bitmap((System.Drawing.Image)bmp, width, height);

                Graphics g = Graphics.FromImage(thumb2); // Create Graphics object from original Image

                        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                        //Set Image codec of JPEG type, the index of JPEG codec is "1"
                        System.Drawing.Imaging.ImageCodecInfo codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1];
                        //Set the parameters for defining the quality of the thumbnail... here it is set to 100%
                        System.Drawing.Imaging.EncoderParameters eParams = new System.Drawing.Imaging.EncoderParameters(1);
                        eParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
                        //Now draw the image on the instance of thumbnail Bitmap object
                        g.DrawImage(bmp, new Rectangle(0, 0, thumb2.Width, thumb2.Height));
                        thumb2.Save(thumbnailFilePath, codec, eParams);
                        g.Dispose();
                        thumb2.Dispose();
            NewBildesString = BildePath + NewbildeName;
            return NewBildesString;
            bmp.Dispose();
        }

    public string MakeMeAGoodThumbnailO(string pathUplode, System.IO.Stream Object, string FileName, int SizeH, int SizeW)
    { // koments:  string pathUplode formāts = "C:\\UploadedUserFiles\\" .
        bool Horizontal = false;
        bool XYmode = false;
        float Procents = 0;
        // bool Vertical = false;
        System.Drawing.Bitmap bmp2 = new System.Drawing.Bitmap(Object);
        float bmpH = Convert.ToSingle(bmp2.Height);
        float bmpW = Convert.ToSingle(bmp2.Width);
        if (SizeH != 0)
        {
            Horizontal = true; //Size = SizeH;
            Size1 = SizeH;
            if (SizeW != 0)
            { // Salīdzina Proporcijas Bildei Vs PARAMETRiem
                XYmode = true;
                float S = Convert.ToSingle(SizeW);
                float T = Convert.ToSingle(SizeH);
                //float A = (S / T)*1000; // Convert.ToSingle(SizeW / SizeH);
                //float B =  (bmpW /bmpH)*1000;
                //int A = bmp2.Height;
                //int B = bmp2.Width;
                int A = Convert.ToInt32((SizeW * 1000) / SizeH);
                int B = ((bmp2.Width * 1000) / bmp2.Height);

                if (A < B)
                {
                    Horizontal = false;
                    Size1 = SizeW;
                }
                else
                {
                    Horizontal = true;
                    Size1 = SizeH;
                }
            }
        }
        else
        {
            if (SizeW != 0) { Size1 = SizeW; Horizontal = false; }
        }

        //if (SizeH != 0)
        //{ Horizontal = true; Size1 = SizeH; }
        //if (SizeW != 0) { Size1 = SizeW; }
        // Size = SizeW;
        string NewBildesString = "";
        // System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(FileField.FileContent);

        Int32 width, height;

        try
        {
            bmp2.Save(pathUplode + FileName); // save Image Orģināju
        }
        catch (Exception exp)
        {
            throw new Exception("Failu Nevar Saglabāt");
        }

        IstaisBildesString = BildePath + FileName;

        //these are just arbitary numbers -- if the image is larger than this, create a 100px max by 100px max thumbnail defined by the constant at the start
        if (bmp2.Height > SizeH && bmp2.Width > SizeW)
        {
            float percent = 0;
            if (Horizontal == true)
            {
                percent = DeterminePercentageForResize(bmp2.Height);
            }
            else { percent = DeterminePercentageForResize(bmp2.Width); }

            float floatWidth = (float)bmp2.Width * percent;
            float floatHeight = (float)bmp2.Height * percent;
            width = Convert.ToInt32(floatWidth);
            height = Convert.ToInt32(floatHeight);
        }
        else
        {
            width = Convert.ToInt32(bmpW);
            height = Convert.ToInt32(bmpH);
        }
        string NewbildeName = FileName; // bez File Name
        //Size newSize = new Size(width, height);
        string thumbnailFilePath = string.Empty;
        thumbnailFilePath = pathUplode + NewbildeName; //Change the thumbnail path if you want
        bmp2.Dispose();
        System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(Object);
        System.Drawing.Bitmap thumb2 = new System.Drawing.Bitmap((System.Drawing.Image)bmp, width, height);

        Graphics g = Graphics.FromImage(thumb2); // Create Graphics object from original Image

        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
        //Set Image codec of JPEG type, the index of JPEG codec is "1"
        System.Drawing.Imaging.ImageCodecInfo codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1];
        //Set the parameters for defining the quality of the thumbnail... here it is set to 100%
        System.Drawing.Imaging.EncoderParameters eParams = new System.Drawing.Imaging.EncoderParameters(1);
        eParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
        //Now draw the image on the instance of thumbnail Bitmap object
        g.DrawImage(bmp, new Rectangle(0, 0, thumb2.Width, thumb2.Height));
        thumb2.Save(thumbnailFilePath, codec, eParams);
        g.Dispose();
        thumb2.Dispose();
        NewBildesString = BildePath + NewbildeName;
        return NewBildesString;
        bmp.Dispose();
    }
 

    private float DeterminePercentageForResize(int size2)
    {
        float percent = (float)Size1 / (float)size2;  // Tagat dala pēc Augstuma !! 

        if (percent > 1 && percent != 0)
            throw new Exception("Percent cannot be greater than 1 or equal to zero");
        else
            return percent;
    }

    private bool ThumbnailCallback()
    {
        return false;
    }

    // *************************************************************
    public String MakeShortText(string Rtext_in, int BurtuSkaits)
    {
        string shortText = ShortTextFunction(Rtext_in,BurtuSkaits) ;
   //     string smal_text = tag_text[0] + shortText; // Šis kods uztaisa ka Embed vidaks Rādās Default Lapā
        string smal_text = shortText; // Šeit Embed Vidaks Vairs Nerādās Default lapā, tikai DefaultZoom lapā
        return smal_text;
    }

    public string MakeShortTagFreeText(string text_in, int BurtuSkaits_in)
    {
        string smal_text = ShortTextFunction(text_in,BurtuSkaits_in);
        // Tālāk noņem nost <br/> tagu!!
        char[] RinduDalitajs = { '\n' };
        char[] SpaceDalitajs = { ' ' };
        char[] tagDalitajs = { '<', '>' };
        string JaunsTagFreeTeksts = "";  // jaunais Samazinātais Tag free Teksts;
        // sadala teksta rindas atsevišķos array laokos
        string[] RinduTeksts = smal_text.Split(RinduDalitajs);
        for (int i = 0; i < RinduTeksts.Length; i++)
        {
            // sadala rindu pa vārdiem katrs vārds atrodās instrukcijas array laukā 
            string[] VardaLauks = RinduTeksts[i].Split(SpaceDalitajs);
            for (int ii = 0; ii < VardaLauks.Length; ii++)
            {
                string Vards = VardaLauks[ii];
                if (VardaLauks[ii].Contains("<br/>") == false)
                {
                    JaunsTagFreeTeksts += VardaLauks[ii] + " ";
                }
                else
                {
                    string[] tagfree = VardaLauks[ii].Split(tagDalitajs);
                    foreach(string p in tagfree)
                    {
                        if (p.Contains("br/") == false)
                        {
                        JaunsTagFreeTeksts += p;
                        }
                    }
                }
            }
        }
        return JaunsTagFreeTeksts;
    }

    private string ShortTextFunction(string Rtext_in, int BurtuSkaits)
    {
        // izgriež no teksta ārā visus tagus (pagaidām tikai <object un <a ;
        Text_tag_filter(Rtext_in, "<object", "</object>", 0); // Pirmais filtrs
        Text_tag_filter(Rtext, "<iframe", "</iframe>", 0); // velreiz filtrē Uz Iframe tagu.
        bool tag_ir = true;
        int a = 1;
        while (tag_ir == true)
        {
            tag_ir = Text_tag_filter(Rtext, "<a", "</a>", a++); // otrais filtrs
        }
        tag_ir = false;
        while (tag_ir == true)
        {
            tag_ir = Text_tag_filter(Rtext, "<object", "</object>", a++); // otrais filtrs
            tag_ir = Text_tag_filter(Rtext, "<iframe", "</iframe>", 0);
        }

        // tālāk TĪRO Rtext sadala mazajā tekstā :) 

        char[] RinduDalitajs = {'\n'};
        char[] SpaceDalitajs = {' ' };
        string JaunsTeksts = "";  // jaunais Samazinātais Teksts;
        // sadala teksta rindas atsevišķos array laokos
        string[] RinduTeksts = Rtext.Split(RinduDalitajs);
        int burti = BurtuSkaits;
        int burtuSkaits = 0;
        for (int i = 0; i < RinduTeksts.Length; i++)
        {
            // sadala rindu pa vārdiem katrs vārds atrodās instrukcijas array laukā 
            string[] VardaLauks = RinduTeksts[i].Split(SpaceDalitajs);

            //if (i == (RinduTeksts.Length - 1))
            //{
            //    beigas = true;
            //}
            // sāk filtrēt katru rindas vārdu ko tas nozīmē un kādus apreiķinus jāveic!!
            for (int ii = 0; ii < VardaLauks.Length; ii++)
            {
                string Vards = VardaLauks[ii];
                burtuSkaits += Vards.Length + 1; // skaitam arī klāt atstarpi !!

                if (burti <= burtuSkaits)
                {
                    break;
                }
                else
                {
                    JaunsTeksts += VardaLauks[ii] + " ";
                }
            }
            if (burti <= burtuSkaits)
            {
                JaunsTeksts += " ...";
                break;
            }
        }
        string smal_text = JaunsTeksts;
        return smal_text;
    }

    private bool Text_tag_filter(string inText, string Tag_start, string Tag_end, int tag_start_Nr_array_index)
    {
        string cut_txt = "";
        //int tag_start_Nr = 0;
        bool Tag_true = false;
        int tag_end_length = Tag_end.Length;
        if (inText.Contains(Tag_start) == true)
        {
            if (tag_start_Nr.Length < tag_start_Nr_array_index + 1) // array resize ja vaig!
            {
                Array.Resize(ref tag_start_Nr, tag_start_Nr_array_index + 1);
                Array.Resize(ref tag_text, tag_start_Nr_array_index + 1);
            }
            Tag_true = true;
            tag_start_Nr[tag_start_Nr_array_index] = inText.IndexOf(Tag_start);
            int tag_end_Nr = inText.IndexOf(Tag_end);
            // tālāk izfiltrē no teiksta šito Vimeo vidaku !! :)
            cut_txt = inText.Substring(0, tag_start_Nr[tag_start_Nr_array_index]) + inText.Substring(tag_end_Nr + tag_end_length, inText.Length - tag_end_Nr - tag_end_length); //
            Rtext = cut_txt;
            tag_text[tag_start_Nr_array_index] = inText.Substring(tag_start_Nr[tag_start_Nr_array_index], tag_end_Nr - tag_start_Nr[tag_start_Nr_array_index] + tag_end_length);
        }
        else { Rtext = inText; }
        return Tag_true;

        // šito jāpielabo (+9 vieta):  inText.Substring(tag_end_Nr + 9, inText.Length - tag_end_Nr - 9)
    }


}
